package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"user_bff/pkg"
)

func UserAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": -1,
				"msg":  "token为空",
				"data": nil,
			})
			return
		}
		payload, f, err := pkg.GetJwtTokenPayload(token)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": -1,
				"msg":  "token解析失败",
				"data": nil,
			})
			return
		}
		//判断token 是否过期
		timer := time.Unix(int64(f), 0)
		if time.Now().After(timer) {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": -1,
				"msg":  "token已过期",
				"data": nil,
			})
			return
		}
		//存储token
		c.Set("userId", payload)
		c.Next()
	}
}
